#include <iostream>
#include <list>
#include <unordered_map>

using namespace std;

class LRUCache {
private:
    int capacity;
    list<pair<int, int>> cache;
    unordered_map<int, list<pair<int, int>>::iterator> hash_map;
public:
    LRUCache(int capacity) {
        this->capacity = capacity;
    }
    int get(int key) {
        unordered_map<int, list<pair<int, int>>::iterator>::iterator find_result = hash_map.find(key);
        if (find_result == hash_map.end()) {
            return -1;
        }
        cache.splice(cache.begin(), cache, find_result->second);
        return find_result->second->second;
    }
    void put(int key, int value) {
        unordered_map<int, list<pair<int, int>>::iterator>::iterator find_result = hash_map.find(key);
        if (find_result == hash_map.end()) {
            if (cache.size() == capacity) {
                hash_map.erase(cache.back().first);
                cache.pop_back();
            }
            cache.push_front({key, value});
            hash_map[key] = cache.begin();
        } else {
            find_result->second->second = value;
            cache.splice(cache.begin(), cache, find_result->second);
        }
    }
};


int main() {
    LRUCache cache = LRUCache( 2 /* 缓存容量 */ );
    cache.put(1, 1);
    cache.put(2, 2);
    int o = cache.get(1);       // 返回  1
    cout << o << endl;
    cache.put(3, 3);    // 该操作会使得密钥 2 作废
    o = cache.get(2);       // 返回 -1 (未找到)
    cout << o << endl;
    cache.put(4, 4);    // 该操作会使得密钥 1 作废
    o = cache.get(1);       // 返回 -1 (未找到)
    cout << o << endl;
    o = cache.get(3);       // 返回  3
    cout << o << endl;
    o = cache.get(4);       // 返回  4
    cout << o << endl;
}